package com.gp.library.manager;

import android.content.Context;
import android.content.pm.PackageManager;

import com.tencent.mmkv.MMKV;

/**
 * Created by jackdeng on 2020/1/3.
 */

public class MMKVManager {
    private static MMKV mmkv;

    private MMKVManager() {
    }

    public static void init(Context context) {
        MMKV.initialize(context);
        mmkv = MMKV.defaultMMKV();
    }

    public static void initShared(String id, Context context) {
        MMKV.initialize(context);
        mmkv = MMKV.mmkvWithID(id, MMKV.MULTI_PROCESS_MODE);
    }

    public static void initShared(String id, String rootPath) {
        MMKV.initialize(rootPath + "/mmkv");
        mmkv = MMKV.mmkvWithID(id, MMKV.MULTI_PROCESS_MODE);
    }

    public static void initShared(String id, Context context, String remotePackageName) {
        try {
            context = context.createPackageContext(remotePackageName, Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        initShared(id, context);
    }

    public static void exit() {
        if (checkValid())
            MMKV.onExit();
    }

    private static boolean checkValid() {
        return mmkv != null;
    }

    public static void put(String key, String value) {
        if (checkValid())
            mmkv.encode(key, value);
    }

    public static void put(String key, int value) {
        if (checkValid())
            mmkv.encode(key, value);
    }

    public static void put(String key, boolean value) {
        if (checkValid())
            mmkv.encode(key, value);
    }

    public static void put(String key, float value) {
        if (checkValid())
            mmkv.encode(key, value);
    }

    public static void put(String key, long value) {
        if (checkValid())
            mmkv.encode(key, value);
    }

    public static String get(String key, String defaultValue) {
        if (checkValid())
            return mmkv.decodeString(key, defaultValue);
        else
            return defaultValue;
    }

    public static int get(String key, int defaultValue) {
        if (checkValid())
            return mmkv.decodeInt(key, defaultValue);
        else
            return defaultValue;
    }

    public static boolean get(String key, boolean defaultValue) {
        if (checkValid())
            return mmkv.decodeBool(key, defaultValue);
        else
            return defaultValue;
    }

    public static float get(String key, float defaultValue) {
        if (checkValid())
            return mmkv.decodeFloat(key, defaultValue);
        else
            return defaultValue;
    }

    public static long get(String key, long defaultValue) {
        if (checkValid())
            return mmkv.decodeLong(key, defaultValue);
        else
            return defaultValue;
    }
}
